<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：shop.guanjunbang.cn
 * 授权域名：shop.guanjunbang.cn
 * 授权码：vdcajlVLIVAgVdkfJvgY
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

namespace app\common;
use think\facade\Db;
use think\facade\Log;


class Member
{
    //升级
	public static function uplv($aid,$mid){
		$member = Db::name('member')->where('aid',$aid)->where('id',$mid)->find();
        if(!$member['id']) return;
		self::douplv($aid,$member);
		//他的上级
		if($member['path']){
			$parentList = Db::name('member')->where('aid',$aid)->where('id','in',$member['path'])->order(Db::raw('field(id,'.$member['path'].')'))->select()->toArray();
			if($parentList){
				$parentList = array_reverse($parentList);
				foreach($parentList as $parent){
					self::douplv($aid,$parent);
				}
			}
		}
	}
    /*
    *等级升级
    */
    public static function douplv($aid,$member){
		$mid = $member['id'];
        $wxpaymoney = 0 + Db::name('wxpay_log')->where('aid',$aid)->where('mid',$mid)->sum('total_fee');
        $ordermoney = 0 + Db::name('shop_order')->where('aid',$aid)->where('mid',$mid)->where('status','in','1,2,3')->sum('totalprice');
        $rechargemoney = 0 + Db::name('recharge_order')->where('aid',$aid)->where('mid',$mid)->where('status',1)->sum('money');

        self::upLevel($aid, $member, $member, $ordermoney, $wxpaymoney, $rechargemoney);

        //其他分组等级
        }

    /**
     * @param $aid
     * @param $member
     * @param $levelInfo 等级信息 levelid,levelstarttime
     * @param $ordermoney
     * @param $wxpaymoney
     * @param $rechargemoney
     * @param $cid 其他分组等级为空时使用此字段
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function upLevel($aid, $member, $levelInfo, $ordermoney, $wxpaymoney, $rechargemoney, $cid = 0)
    {
        $mid = $member['id'];
        $nowlv = ['sort' => -1];
        if($levelInfo['levelid'])
            $nowlv = Db::name('member_level')->where('aid',$aid)->where('id',$levelInfo['levelid'])->find();
        $cid = $cid ? $cid : $nowlv['cid'];
        //等级列表
        $lvlist = Db::name('member_level')->where('aid',$aid)->where('cid', $cid)->where('can_up',1)->where('sort','>',$nowlv['sort'])->order('sort,id')->select();
        $newlv = $nowlv;
        foreach($lvlist as $lv){
            $isup = false;
            $condition_or = false;
			if($lv['maxnum'] > 0){
				$lvmembercount = Db::name('member')->where('aid',$aid)->where('levelid',$lv['id'])->count();
				if($lvmembercount >= $lv['maxnum']) continue;
			}
            if(($lv['up_ordermoney']>0 && $lv['up_ordermoney'] <= $ordermoney) || ($lv['up_wxpaymoney']>0 && $lv['up_wxpaymoney'] <= $wxpaymoney)|| ($lv['up_rechargemoney']>0 && $lv['up_rechargemoney'] <= $rechargemoney) || ($member['card_code'] && $lv['up_getmembercard']==1)){
                $isup = true;
            }
            if(!$isup && $lv['up_fxordermoney'] > 0 && $lv['up_fxorder_condition'] == 'or'){
				if($lv['up_fxordermoney_removemax'] ==1){
					$downmids = self::getdownmids_removemax($aid,$mid,$lv['up_fxorderlevelnum'],$lv['up_fxorderlevelid']);
					//\think\facade\Log::write('---'.$mid.'去除最高的业绩后会员id---');
					//\think\facade\Log::write($downmids);
				}else{
					$downmids = self::getdownmids($aid,$mid,$lv['up_fxorderlevelnum'],$lv['up_fxorderlevelid']);
				}
                $fxordermoney = 0 + Db::name('shop_order_goods')->where('status','in','1,2,3')->where('mid','in',$downmids)->sum('totalprice');
                if($fxordermoney >= $lv['up_fxordermoney']){
                    $isup = true;
                }
            }
            if(!$isup && $lv['up_fxordermoney_xiao'] > 0){
                $downmids = self::getdownmids_xiao($aid,$mid,$lv['up_fxorderlevelnum_xiao'],$lv['up_fxorderlevelid_xiao']);
                $fxordermoney = 0 + Db::name('shop_order_goods')->where('status','in','1,2,3')->where('mid','in',$downmids)->sum('totalprice');
                if($fxordermoney >= $lv['up_fxordermoney_xiao']){
                    $isup = true;
                }
            }
            if(!$isup && ($lv['up_fxdowncount']>0 || $lv['up_fxdowncount2']>0 || $lv['up_fxdowncount3']>0)){
                $downmidcount1 = 0;
                $downmidcount2 = 0;
                $downmidcount3 = 0;
                $up_fxdowncount = intval($lv['up_fxdowncount']);
                $up_fxdowncount2 = intval($lv['up_fxdowncount2']);
                $up_fxdowncount3 = intval($lv['up_fxdowncount3']);
                if($lv['up_fxdowncount'] > 0){
                    $downmids = self::getdownmids($aid,$mid,$lv['up_fxdownlevelnum'],$lv['up_fxdownlevelid']);
                    $downmidcount1 = count($downmids);
                }
                if($lv['up_fxdowncount2'] > 0){
                    $downmids2 = self::getdownmids($aid,$mid,$lv['up_fxdownlevelnum2'],$lv['up_fxdownlevelid2']);
                    $downmidcount2 = count($downmids2);
                }
                if($lv['up_fxdowncount3'] > 0){
                    $downmids3 = self::getdownmids($aid,$mid,$lv['up_fxdownlevelnum3'],$lv['up_fxdownlevelid3']);
                    $downmidcount3 = count($downmids3);
                }
                if($downmidcount1 >= $up_fxdowncount && $downmidcount2 >= $up_fxdowncount2 && $downmidcount3 >= $up_fxdowncount3){
                    $isup = true;
                }
            }
			if(!$isup && ($lv['up_proid']!='0' && $lv['up_proid']!='')){ //购买指定商品
                $up_proids = explode(',',str_replace('，',',',$lv['up_proid']));
                $up_pronums = explode(',',str_replace('，',',',$lv['up_pronum']));
                if(count($up_pronums) > 1) {
                    foreach($up_proids as $k=>$up_proid){
                        $pronum = $up_pronums[$k];
                        if(!$pronum) $pronum = 1;
                        $buynum = Db::name('shop_order_goods')->where('aid',$aid)->where('mid',$mid)->where('proid',$up_proid)->where('status','in','1,2,3')->sum('num');
                        if($buynum >= $pronum){
                            $isup = true;
//                        break;
                        }
                    }
                } else {
                    $pronum = $up_pronums[0];
                    if(!$pronum) $pronum = 1;
                    $buynum = 0;
                    foreach($up_proids as $k=>$up_proid){
                        $buynum += Db::name('shop_order_goods')->where('aid',$aid)->where('mid',$mid)->where('proid',$up_proid)->where('status','in','1,2,3')->sum('num');
                        if($buynum >= $pronum){
                            $isup = true;
//                        break;
                        }
                    }
                }
            }
            //是否包含or的条件
            if($lv['up_ordermoney']>0 || $lv['up_wxpaymoney']>0 || $lv['up_rechargemoney']>0 || $lv['up_getmembercard']==1 || ($lv['up_fxordermoney'] > 0 && $lv['up_fxorder_condition'] == 'or') || $lv['up_fxordermoney_xiao'] > 0
             || $lv['up_fxdowncount']>0 || $lv['up_fxdowncount2']>0 || $lv['up_fxdowncount3']>0 || ($lv['up_proid']!='0' && $lv['up_proid']!='')) {
                $condition_or = true;
            }

            if(($isup || ($isup === false && $condition_or === false)) && $lv['up_fxordermoney'] > 0 && $lv['up_fxorder_condition'] == 'and'){
				if($lv['up_fxordermoney_removemax'] ==1){
					$downmids = self::getdownmids_removemax($aid,$mid,$lv['up_fxorderlevelnum'],$lv['up_fxorderlevelid']);
				}else{
					$downmids = self::getdownmids($aid,$mid,$lv['up_fxorderlevelnum'],$lv['up_fxorderlevelid']);
				}
                $fxordermoney = 0 + Db::name('shop_order_goods')->where('status','in','1,2,3')->where('mid','in',$downmids)->sum('totalprice');
                if($fxordermoney >= $lv['up_fxordermoney']){
                    $isup_up_fxordermoney = true;
                } else {
                    $isup = false;
                }
            }
			if(false){}else{
				//没设置或条件$isup === false && $condition_or === false
				if(($isup || ($isup === false && $condition_or === false)) && ($lv['up_fxdowncount_and']>0 || $lv['up_fxdowncount2_and']>0)){
					$downmidcount1 = 0;
					$downmidcount2 = 0;
					$up_fxdowncount = intval($lv['up_fxdowncount_and']);
					$up_fxdowncount2 = intval($lv['up_fxdowncount2_and']);
					if($lv['up_fxdowncount_and'] > 0){
						$downmids = self::getdownmids($aid,$mid,$lv['up_fxdownlevelnum_and'],$lv['up_fxdownlevelid_and']);
						$downmidcount1 = count($downmids);
					}
					if($lv['up_fxdowncount2_and'] > 0){
						$downmids2 = self::getdownmids($aid,$mid,$lv['up_fxdownlevelnum2_and'],$lv['up_fxdownlevelid2_and']);
						$downmidcount2 = count($downmids2);
					}
					if($downmidcount1 >= $up_fxdowncount && $downmidcount2 >= $up_fxdowncount2){
						$isup_up_fxdowncount_and = true;
					} else {
						$isup = false;
					}
				}
			}
            if($isup || ($isup === false && $condition_or === false)) {
                if(($lv['up_fxordermoney'] > 0 && $lv['up_fxorder_condition'] == 'and') && ($lv['up_fxdowncount_and']>0 || $lv['up_fxdowncount2_and']>0)) {
                    if($isup_up_fxordermoney && $isup_up_fxdowncount_and) {
                        $isup = true;
                    }
                }elseif(!($lv['up_fxordermoney'] > 0 && $lv['up_fxorder_condition'] == 'and') && ($lv['up_fxdowncount_and']>0 || $lv['up_fxdowncount2_and']>0)) {
                    if($isup_up_fxdowncount_and) {
                        $isup = true;
                    }
                }elseif(($lv['up_fxordermoney'] > 0 && $lv['up_fxorder_condition'] == 'and') && !($lv['up_fxdowncount_and']>0 || $lv['up_fxdowncount2_and']>0)) {
                    if($isup_up_fxordermoney) {
                        $isup = true;
                    }
                }
            }
            if($isup) $newlv = $lv;
        }

        if($newlv && $newlv['id'] != $levelInfo['levelid']) {
            if ($newlv['yxqdate'] > 0) {
                $levelendtime = strtotime(date('Y-m-d')) + 86400 + 86400 * $newlv['yxqdate'];
            } else {
                $levelendtime = 0;
            }
            //判断是否默认分组
            if($newlv['cid'] > 0)
                $is_default = Db::name('member_level_category')->where('id', $newlv['cid'])->value('isdefault');
            if ($is_default || $newlv['cid'] == 0) {
                Db::name('member')->where('aid', $aid)->where('id', $mid)->update(['levelid' => $newlv['id'], 'levelendtime' => $levelendtime]);
                if(false){}else {
                    Db::name('member')->where('aid', $aid)->where('id', $mid)->update(['levelstarttime' => time()]);
                }
            } else {
                }

            Wechat::updatemembercard($aid, $mid);
            //赠送积分
            if($newlv['up_give_score'] > 0) {
                self::addscore($aid, $mid, $newlv['up_give_score'], '升级奖励');
            }
            //奖励佣金
            if($newlv['up_give_commission'] > 0) {
                self::addcommission($aid,$mid,0,$newlv['up_give_commission'],'升级奖励');
            }
            //奖励余额
            if($newlv['up_give_money'] > 0) {
                self::addmoney($aid,$mid,$newlv['up_give_money'],'升级奖励');
            }
            //赠送上级佣金
            if($newlv['up_give_parent_money'] > 0 && $member['pid']) {
                self::addcommission($aid, $member['pid'], $mid, $newlv['up_give_parent_money'], '直推奖');
            }
			
			if($newlv['up_give_parent_coupon_ids'] && $newlv['up_give_parent_coupon_nums'] && $member['pid']){
				$coupon_ids = explode(',',$newlv['up_give_parent_coupon_ids']);
				$coupon_nums = explode(',',$newlv['up_give_parent_coupon_nums']);
				if($coupon_ids){
					foreach($coupon_ids as $ck=>$coupon_id){
						if(!$coupon_nums[$ck]){
							$coupon_nums[$ck] = 1;
						}
						for($i=0;$i<$coupon_nums[$ck];$i++){
							\app\common\Coupon::send($aid,$member['pid'],$coupon_id,true);
						}
					}
				}
			}

			//升级赠送优惠券
            //升级记录
            $order = [
                'aid' => $aid,
                'mid' => $mid,
                'from_mid' => $mid,
                'levelid' => $newlv['id'] ,
                'title' => '自动升级',
                'totalprice' => 0,
                'createtime' => time(),
                'levelup_time' => time(),
                'beforelevelid' => $levelInfo['levelid'],
                'form0' => '类型^_^自动升级',
                'platform' => platform,
                'status' => 2
            ];
            Db::name('member_levelup_order')->insert($order);

            $tmplcontent = [];
            $tmplcontent['first'] = '恭喜您成功升级为'.$newlv['name'];
            $tmplcontent['remark'] = '点击进入查看~';
            $tmplcontent['keyword1'] = $newlv['name']; //会员等级
            $tmplcontent['keyword2'] = '已生效';//审核状态
            $rs = \app\common\Wechat::sendtmpl($aid,$mid,'tmpl_uplv',$tmplcontent,m_url('pages/my/usercenter', $aid));

			}

        if(!$isup && $newlv['id'] == $nowlv['id']){
            }
    }

    //加余额
    public static function addmoney($aid,$mid,$money,$remark){
        if($money==0) return ;
        $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->lock(true)->find();
        if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];

        if(false){}else {
            $after = $member['money'] + $money;
            Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['money'=>$after]);
        }

        $data = [];
        $data['aid'] = $aid;
        $data['mid'] = $mid;
        $data['money'] = $money;
        $data['after'] = $after;
        $data['createtime'] = time();
        $data['remark'] = $remark;
        Db::name('member_moneylog')->insert($data);
        self::uplv($aid,$mid);
        Wechat::updatemembercard($aid,$mid);

		// $tmplcontent = [];
		// $tmplcontent['first'] = '您的'.t('余额').'发生变动，变动金额：'.$money;
		// $tmplcontent['remark'] = '点击进入查看~';
		// $tmplcontent['keyword1'] = date('Y-m-d H:i'); //变动时间
		// $tmplcontent['keyword2'] = $remark;  //变动类型
		// $tmplcontent['keyword3'] = (string) round($money,2);  //变动金额
		// $tmplcontent['keyword4'] = (string) round($after,2);  //当前余额
		// $rs = \app\common\Wechat::sendtmpl($aid,$mid,'tmpl_moneychange',$tmplcontent,m_url('pages/my/usercenter', $aid));
       
        return ['status'=>1,'msg'=>''];
    }
    //加积分
    //@update 22-7-21 增加渠道
    public static function addscore($aid,$mid,$score,$remark,$channel=''){
        if($score==0) return ;
        $score = intval($score);
        $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->lock(true)->find();
        if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];
		$member['score'] = self::getscore($member);
        if($score < 0 && $member['score'] < $score*-1) return ['status'=>0,'msg'=>t('积分').'不足'];

        if(false){}else {
            $after = $member['score'] + $score;
            Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['score'=>$after]);
        }

        $data = [];
        $data['aid'] = $aid;
        $data['mid'] = $mid;
        $data['score'] = $score;
        $data['after'] = $after;
        $data['createtime'] = time();
        $data['remark'] = $remark;
        $data['type'] = 1;
        $data['channel'] = $channel;
        Db::name('member_scorelog')->insert($data);
        Wechat::updatemembercard($aid,$mid,$remark);
        return ['status'=>1,'msg'=>''];
    }
    //加提现积分
    public static function addscore_withdraw($aid,$mid,$score,$remark){
        if($score==0) return ;
        $score = intval($score);
        $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->lock(true)->find();
        if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];
        if($score < 0 && $member['score_withdraw'] < $score*-1) return ['status'=>0,'msg'=>t('积分').'不足'];

        $after = $member['score_withdraw'] + $score;
        Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['score_withdraw'=>$after]);

        $data = [];
        $data['aid'] = $aid;
        $data['mid'] = $mid;
        $data['score'] = $score;
        $data['after'] = $after;
        $data['createtime'] = time();
        $data['remark'] = $remark;
        $data['type'] = 2;
        Db::name('member_scorelog')->insert($data);
        return ['status'=>1,'msg'=>''];
    }
    //加佣金
    public static function addcommission($aid,$mid,$frommid,$commission,$remark,$addtotal=1,$fhtype=''){
        if($commission==0) return ;
        $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->lock(true)->find();
        if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];

		$set = Db::name('admin_set')->where('aid',$aid)->find();
		if($commission > 0 && $set['commission2scorepercent'] > 0){
			$oldcommission = $commission;
			$commission = round($commission * (1-$set['commission2scorepercent']*0.01),2);
			$score = $oldcommission - $commission;
			self::addscore($aid,$mid,$score,$remark);
		}

        if($commission > 0 && $addtotal==1){
            $totalcommission = $member['totalcommission'] + $commission;
        }else{
            $totalcommission = $member['totalcommission'];
        }
        $after = $member['commission'] + $commission;
        $update_member = ['totalcommission'=>$totalcommission,'commission'=>$after];
        if($fhtype == 'fenhong') {
            $update_member['total_fenhong_partner'] = $member['total_fenhong_partner'] + $commission;
            $update_member['total_fenhong'] = $member['total_fenhong'] + $commission;
        } elseif($fhtype == 'teamfenhong') {
            $update_member['total_fenhong_team'] = $member['total_fenhong_team'] + $commission;
            $update_member['total_fenhong'] = $member['total_fenhong'] + $commission;
        } elseif($fhtype == 'level_teamfenhong') {
            $update_member['total_fenhong_level_team'] = $member['total_fenhong_level_team'] + $commission;
            $update_member['total_fenhong'] = $member['total_fenhong'] + $commission;
        } elseif($fhtype == 'areafenhong') {
            $update_member['total_fenhong_area'] = $member['total_fenhong_area'] + $commission;
            $update_member['total_fenhong'] = $member['total_fenhong'] + $commission;
        }
        Db::name('member')->where('aid',$aid)->where('id',$mid)->update($update_member);

        $data = [];
        $data['aid'] = $aid;
        $data['mid'] = $mid;
        $data['frommid'] = $frommid;
        $data['commission'] = $commission;
        $data['after'] = $after;
        $data['createtime'] = time();
        $data['remark'] = $remark;
        Db::name('member_commissionlog')->insert($data);
		
		return ['status'=>1,'msg'=>''];
    }

    //获取余额
    public static function getmoney($member){
        if(!$member || !$member['id']) return '0.00';
        $member = db('member')->where(['id'=>$member['id']])->find();
        return $member['money'];
    }
    //获取积分
    public static function getscore($member){
        if(!$member || !$member['id']) return '0';
        $member = db('member')->where(['id'=>$member['id']])->find();

        return $member['score'];
    }

    public static function addw7moneyscore($aid,$member,$type,$money,$remark){
        $w7uniacid = db('admin_set')->where(['aid'=>$aid])->value('w7uniacid');
        if(empty($w7uniacid)) {
            return ['status'=>0,'msg'=>'w7uniacid empty'];
        }
        $fansinfo = Db::connect('w7')->table('ims_mc_mapping_fans')->where("uniacid='{$w7uniacid}' and (openid='{$member['mpopenid']}' or (unionid!='' && unionid is not null && unionid='{$member['unionid']}') or (openid!='' && openid is not null && openid='{$member['wxopenid']}'))")->find();
//        Log::write([
//            'file' => __FILE__,
//            'line' => __LINE__,
//            '$member' => $member,
//            '$fansinfo' => $fansinfo,
//            'sql' =>  Db::connect('w7')->table('ims_mc_mapping_fans')->getLastSql()
//        ]);
        $openid = $member['mpopenid'];
        if(!$openid) $openid = $member['unionid'];
        if(!$openid) $openid = $member['wxopenid'];
        if(!$fansinfo){
            $rec = array();
            $rec['acid'] = $w7uniacid;
            $rec['uniacid'] = $w7uniacid;
            $rec['openid'] = '';//$openid
            $rec['nickname'] = $member['nickname'];
            $rec['unionid'] = $member['unionid'];
            $rec['follow'] = $member['subscribe'] ? 1 : 0;
            $rec['followtime'] = $member['subscribe_time'] ? $member['subscribe_time'] : $member['createtime'];
            $rec['tag'] = base64_encode(serialize([
                'openid'=>$openid,
                'nickname'=>$member['nickname'],
                'sex'=>$member['sex'],
                'province'=>$member['province'],
                'city'=>$member['city'],
                'country'=>$member['country'],
                'unionid'=>$member['unionid'],
                'subscribe'=>$member['subscribe'],
                'subscribe_time'=>$member['subscribe_time'],
            ]));
            $member2 = array();
            $member2['uniacid'] = $w7uniacid;
            $member2['email'] = md5($openid).'@we7.cc';
            $member2['salt'] = random(8);
            $default_groupid = Db::connect('w7')->table('ims_mc_groups')->where(['uniacid'=>$w7uniacid,'isdefault'=>1])->value('groupid');
            $member2['groupid'] = $default_groupid;
            $member2['createtime'] = time();
            $member2['nickname'] = $member['nickname'];
            $member2['avatar'] = $member['headimg'];
            $member2['nationality'] = $member['country'];
            $member2['resideprovince'] = $member['province'];
            $member2['residecity'] = $member['city'];
            $config = include(ROOT_PATH.'config.php');
            $member2['password'] = md5($openid . $member2['salt'] . $config['authkey']);
            $rec['uid'] = Db::connect('w7')->table('ims_mc_members')->insertGetId($member2);
            Db::connect('w7')->table('ims_mc_mapping_fans')->insertGetId($rec);
        }
        $fansinfo = Db::connect('w7')->table('ims_mc_mapping_fans')->where("uniacid='{$w7uniacid}' and (openid='{$member['mpopenid']}' or (unionid!='' && unionid is not null && unionid='{$member['unionid']}') or (openid!='' && openid is not null && openid='{$member['wxopenid']}'))")->find();
        $uid = $fansinfo['uid'];
        $mcmember = Db::connect('w7')->table('ims_mc_members')->where(['uid'=>$uid])->find();
        if($uid == 0 || !$mcmember){
            $member2 = array();
            $member2['uniacid'] = $w7uniacid;
            $member2['email'] = md5($openid).'@we7.cc';
            $member2['salt'] = random(8);
            $default_groupid = Db::connect('w7')->table('ims_mc_groups')->where(['uniacid'=>$w7uniacid,'isdefault'=>1])->value('groupid');
            $member2['groupid'] = $default_groupid;
            $member2['createtime'] = time();
            $member2['nickname'] = $member['nickname'];
            $member2['avatar'] = $member['headimg'];
            $member2['nationality'] = $member['country'];
            $member2['resideprovince'] = $member['province'];
            $member2['residecity'] = $member['city'];
            $config = include(ROOT_PATH.'config.php');
            $member2['password'] = md5($openid . $member2['salt'] . $config['authkey']);
            $uid = Db::connect('w7')->table('ims_mc_members')->insertGetId($member2);
            Db::connect('w7')->table('ims_mc_mapping_fans')->where(['fanid'=>$fansinfo['fanid']])->update(['uid'=>$uid]);
            $mcmember = Db::connect('w7')->table('ims_mc_members')->where(['uid'=>$uid])->find();
        }
        $after = $mcmember['credit'.$type] + $money;
        Db::connect('w7')->table('ims_mc_members')->where(['uid'=>$uid])->update(['credit'.$type=>$after]);
        $data = array(
            'uid' => $uid,
            'credittype' => 'credit'.$type,
            'uniacid' => $w7uniacid,
            'num' => $money,
            'createtime' => time(),
            'operator' => '',
            'module' => 'ddwx_shop',
            'clerk_id' => '',
            'store_id' => '',
            'clerk_type' => 1,
            'remark' => $remark,
            'real_uniacid' => $uid
        );
        Db::connect('w7')->table('ims_mc_credits_record')->insert($data);

        if($type == 2){
            $data = [];
            $data['aid'] = $aid;
            $data['mid'] = $member['id'];
            $data['money'] = $money;
            $data['after'] = $after;
            $data['createtime'] = time();
            $data['remark'] = $remark;
            Db::name('member_moneylog')->insert($data);
            Db::name('member')->where(['aid'=>$aid,'id'=>$member['id']])->update(['money'=>$after]);
            Wechat::updatemembercard($aid,$member['id']);
        }else{
            $data = [];
            $data['aid'] = $aid;
            $data['mid'] = $member['id'];
            $data['score'] = $money;
            $data['after'] = $after;
            $data['createtime'] = time();
            $data['remark'] = $remark;
            Db::name('member_scorelog')->insert($data);
            Db::name('member')->where(['aid'=>$aid,'id'=>$member['id']])->update(['score'=>$after]);
            Wechat::updatemembercard($aid,$member['id'],$remark);
        }

        return ['status'=>1,'msg'=>''];
    }
	//获取多少级以内的下级
	public static function getdownmids($aid,$mid,$levelnum=0,$levelid=0){
		$downmids = [];
		if($levelid == 0){
			$memberlist = Db::name('member')->field('id,path')->where('aid',$aid)->where('find_in_set('.$mid.',path)')->select()->toArray();
		}else{
			$levelid = str_replace('，',',',$levelid);
			$memberlist = Db::name('member')->field('id,path')->where('aid',$aid)->where('levelid','in',$levelid)->where('find_in_set('.$mid.',path)')->select()->toArray();
			}
		foreach($memberlist as $member){
			if($levelnum == 0){
				$downmids[] = $member['id'];
			}else{
				$path = explode(',',$member['path']);
                $path = array_reverse($path);
				$key = array_search($mid,$path);
				if($key!==false && $key < $levelnum){
					$downmids[] = $member['id'];
				}
			}
		}
		return $downmids;
	}
	//获取多少级以内的下级 小区的(即除了人数最多的区的所有区)
	public static function getdownmids_xiao($aid,$mid,$levelnum=0,$levelid=0){
		$childList = Db::name('member')->field('id,path')->where('aid',$aid)->where('pid',$mid)->select()->toArray();

		$downmidsArr = [];
		foreach($childList as $cmember){
			$thisdownmids = self::getdownmids($aid,$cmember['id'],$levelnum,$levelid);
			if(!$thisdownmids){
				$thisdownmids = $cmember['id'];
			}else{
				$thisdownmids[] = $cmember['id'];
			}
			$downmidsArr[] = ['count'=>count($thisdownmids),'mids'=>$thisdownmids];
		}
		$counts = array_column($downmidsArr,'count');
		array_multisort($counts,SORT_DESC,$downmidsArr);

		$downmids = [];
		foreach($downmidsArr as $k=>$v){
			if($k > 0){
				$downmids = array_merge($downmids,$v['mids']);
			}
		}
		return $downmids;
	}

    //获取多少级以内的下级 去除业绩最高的一个
	public static function getdownmids_removemax($aid,$mid,$levelnum=0,$levelid=0){
		$childList = Db::name('member')->field('id,path')->where('aid',$aid)->where('pid',$mid)->select()->toArray();
		$downmidsArr = [];
		foreach($childList as $cmember){
			$thisdownmids = self::getdownmids($aid,$cmember['id'],$levelnum,$levelid);
			if(!$thisdownmids){
				$thisdownmids = [$cmember['id']];
			}else{
				$thisdownmids[] = $cmember['id'];
			}
			//\think\facade\Log::write($thisdownmids);
			$fxordermoney = 0 + Db::name('shop_order_goods')->where('status','in','1,2,3')->where('mid','in',$thisdownmids)->sum('totalprice');
			$downmidsArr[] = ['count'=>count($thisdownmids),'mids'=>$thisdownmids,'fxordermoney'=>$fxordermoney];
		}
		//\think\facade\Log::write($downmidsArr);
		$counts = array_column($downmidsArr,'fxordermoney');
		array_multisort($counts,SORT_DESC,$downmidsArr);
		//\think\facade\Log::write($downmidsArr);

		$downmids = [];
		foreach($downmidsArr as $k=>$v){
			if($k > 0){
				$downmids = array_merge($downmids,$v['mids']);
			}
		}
		return $downmids;
	}
	//获取团队的会员id集合 团队中有和他平级或超过他等级的就跳出
	private static $mids = [];
	public static function getteammids($aid,$mid,$deep,$levelids,$mids=[],$thisdeep=0){
		if($thisdeep == 0){
			self::$mids = [];
		}
		$thisdeep = $thisdeep+1;
		if($thisdeep > $deep) return self::$mids;
		$dowmids = Db::name('member')->where('aid',$aid)->where('pid',$mid)->where('levelid','in',$levelids)->column('id');
		if($dowmids){
			foreach($dowmids as $downmid){
				if(!in_array($downmid,self::$mids)){
					self::$mids[] = $downmid;
					$down2mids = self::getteammids($aid,$downmid,$deep,$levelids,$mids,$thisdeep);
				}
			}
		}
		return self::$mids;
	}

    public static function addHongbaoEverydayEdu($aid,$mid,$money,$remark,$ogid=0){
        if($money==0) return ;
        $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->lock(true)->find();
        if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];

        $after = $member['hongbao_everyday_edu'] + $money;
        Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['hongbao_everyday_edu'=>$after]);

        $data = [];
        $data['aid'] = $aid;
        $data['mid'] = $mid;
        $data['money'] = $money;
        $data['ogid'] = $ogid;
        $data['createtime'] = time();
        $data['remark'] = $remark;
        Db::name('member_hbe_edu_record')->insert($data);
        return ['status'=>1,'msg'=>''];
    }

    public static function addHongbaoLog($aid,$mid,$money,$remark){

        if($money==0) return ;
        $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->find();
        if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];

        $afterTotal = $member['hongbao_ereryday_total'] + $money;

        $data = [];
        $data['aid'] = $aid;
        $data['mid'] = $mid;
        $data['money'] = $money;
        $data['after'] = $afterTotal;
        $data['createtime'] = time();
        $data['remark'] = $remark;
        Db::name('member_hbe_log')->insert($data);
        return ['status'=>1,'msg'=>''];
    }

    //加余额宝
    public static function addyuebaomoney($aid,$mid,$money,$remark,$type=0){

        if($money==0) return ;
        $member = Db::name('member')->where('aid',$aid)->where('id',$mid)->find();
        if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];

        $after = $member['yuebao_money'] + $money;
        Db::name('member')->where('aid',$aid)->where('id',$mid)->update(['yuebao_money'=>$after]);

        $data = [];
        $data['aid'] = $aid;
        $data['mid'] = $mid;
        $data['money'] = $money;
        $data['after'] = $after;
        $data['type']  = $type;
        $data['createtime'] = time();
        $data['remark'] = $remark;
        Db::name('member_yuebao_moneylog')->insert($data);

        return ['status'=>1,'msg'=>''];
    }
    //加元宝
    public static function addyuanbao($aid,$mid,$yuanbao,$remark){
        }
    //加其他余额
    public static function addOtherMoney($aid,$mid,$type,$money,$remark){
        }
}